var express = require('express');
const TodoModel = require('../../module/todoModel');
var router = express.Router();
const moment = require('moment')
const checkTokenMiddleware = require('../../middleware/checkToken')
const {formidable} = require('formidable')
/* GET home page. */
router.get('/todo', checkTokenMiddleware,function (req, res, next) {
    TodoModel.find().sort({ pub_time: -1 }).exec((err, data) => {
        if (err) {
            return res.json({
                code: '1001',
                msg: '读取错误',
                data: null
            })
        }
        res.json({
            code: '0000',
            msg: '读取成功',
            data: data
        })
    })
});

router.post('/todo',checkTokenMiddleware, (req, res) => {

    TodoModel.create({ ...req.body, pub_time: moment(req.pub_time).toDate() }, (err, data) => {
        if (err) {
            return res.json({
                code: '1001',
                msg: '创建错误',
                data: null
            })
        }
        res.json({
            code: '0000',
            msg: '创建成功',
            data: data
        })
    })
})

router.put('/todo/:id',checkTokenMiddleware,(req, res)=>{
    let id = req.params.id
    TodoModel.updateOne({_id:id},req.body,(err,data)=>{
        if (err) {
            return res.json({
                code: '1002',
                msg: '更新错误',
                data: null
            })
        }
        TodoModel.findById(id,(err, data)=>{
            if (err) {
                return res.json({
                    code: '1001',
                    msg: '读取错误',
                    data: null
                })
            }

            res.json({
                code: '0000',
                msg: '更新成功',
                data: data
            })
        })
    })
})

router.post('/upload',(req,res)=>{
    const form = formidable({
        uploadDir:__dirname+'/../../public/images/',
        keepExtensions:true
    })

    form.parse(req, (err, fields, files) => {
        if (err) {
          return res.json({
            code:'4001',
            msg:'表单解析错误',
            data:null
          });
        }
        res.json({
            code:'0000',
            msg:'上传成功',
            data:'http://127.0.0.1:3000/images/'+files.file[0].newFilename});
      });
})

router.delete('/remove/todo/:id',checkTokenMiddleware,(req, res)=>{
    let id = req.params.id
    TodoModel.deleteOne({_id:id},(err,data)=>{
        if(err){
            return res.json({
                code:'4002',
                msg:'删除失败',
                data:null
            })
        }
        res.json({
            code:'0000',
            msg:'删除成功',
            data:null
        })
    })
})

module.exports = router;
